package com.supply.dl.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.supply.dl.R;
import com.supply.dl.app.ApiService;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalAdapter;
import com.supply.dl.app.adapter.RecyclerViewDivider;
import com.supply.dl.app.adapter.ViewHolder;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.BaseObserver;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.BaseBean;
import com.supply.dl.bean.OperateCompanyInfo;
import com.supply.dl.bean.OperateModle;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.utils.DialogUtils;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.utils.T;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作业选择，选择作业公司，作业人员，作业模式，作业费率
 * <p>
 * Author: tian <br>
 * Time: 2018/7/31 14:20
 */
public class OperateSelectActivity extends BaseActivity {

    @BindView(R.id.search_rv)
    RecyclerView search_rv;

    private ArrayList datas;

    private ArrayList datas_cache;

    private NormalAdapter adapter;

    @BindView(R.id.input_et)
    EditText input_et;

    /**
     * 被选中项
     */

    private BaseBean selectBean;

    /**
     * 多选被选中的时候
     */
    private ArrayList selectBeans;

    /**
     * 标记是作业公司还是 作业人员 作业模式，作业费率的选择
     */
    private String action;

    /**
     * 传递过来的 工厂id
     */
    private String factoryId;


    /**
     * 选作业人员的是 传递的公司id
     */
    private String companyId;

    /**
     * 模糊查询
     * @return
     */
    @OnClick(R.id.search)
    public void onClickSearch(){
        if(!TextUtils.isEmpty(input_et.getText().toString())){
            search(input_et.getText().toString());
        }else{
            datas.clear();
            datas.addAll(datas_cache);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 模糊搜索
     */
    private void search(String key){
        T.d("关键字：" + key);
        switch (action) {
            //选择公司
            case AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT:

                ArrayList<OperateCompanyInfo> companyInfos = datas_cache;

                datas.clear(); //清除原数据

                for(OperateCompanyInfo companyInfo : companyInfos){
                    if(companyInfo.getOperateCompany().contains(key)){
                        datas.add(companyInfo); //添加一个搜索缓存
                    }
                }
                adapter.notifyDataSetChanged();

                break;

            //作业人员选择  多选
            case AppConfig.BaseDataAction.OPERATE_PERSON_SELECT:

                List<OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean> persons = datas_cache;

                datas.clear(); //清除原数据

                for(OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean person : persons){
                    if(person.getPersonName().contains(key)){
                        datas.add(person); //添加一个搜索缓存
                    }
                }

                adapter.notifyDataSetChanged();
                break;

            //作业模式选择 多选
            case AppConfig.BaseDataAction.OPERATE_MODL_SELECT:

                List<OperateModle> modes = datas_cache;

                datas.clear(); //清除原数据

                for(OperateModle mode : modes){
                    if(mode.getModeName().contains(key)){
                        datas.add(mode); //添加一个搜索缓存
                    }
                }

                adapter.notifyDataSetChanged();
                break;
        }
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_operate_select;
    }

    @Override
    protected void initView() {
        setTitleShow("物料选择");

        setRightInVisible();
        showLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collectCheck();
            }
        });


        action = getIntent().getStringExtra("action");
        factoryId = getIntent().hasExtra("factoryId") ? getIntent().getStringExtra("factoryId") : "";
        companyId = getIntent().hasExtra("companyId") ? getIntent().getStringExtra("companyId") : "";

        datas = new ArrayList<>();
        datas_cache = new ArrayList();
        adapter = new NormalAdapter<Object>(this, datas) {
            @Override
            protected void convert(ViewHolder holder, Object data) {

                TextView txt_name = holder.getView(R.id.txt_name);
                ImageView state_img = holder.getView(R.id.img_select);

                switch (action) {
                    //选公司
                    case AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT:

                        OperateCompanyInfo item = (OperateCompanyInfo) data;
                        txt_name.setText(item.getOperateCompany());

                        if (item.isSelected()) {
                            state_img.setImageResource(R.mipmap.check_selected);
                        }
                        //
                        else {
                            state_img.setImageResource(R.mipmap.check_normal);
                        }

                        break;

                    //选人员
                    case AppConfig.BaseDataAction.OPERATE_PERSON_SELECT:

                        OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean person =
                                (OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean) data;
                        txt_name.setText(person.getPersonName());

                        if (person.isSelected()) {
                            state_img.setImageResource(R.mipmap.check_selected);
                        }
                        //
                        else {
                            state_img.setImageResource(R.mipmap.check_normal);
                        }
                        break;

                    //选模式
                    case AppConfig.BaseDataAction.OPERATE_MODL_SELECT:

                        OperateModle mode = (OperateModle) data;
                        txt_name.setText(mode.getModeName());

                        if (mode.isSelected()) {
                            state_img.setImageResource(R.mipmap.check_selected);
                        }
                        //
                        else {
                            state_img.setImageResource(R.mipmap.check_normal);
                        }
                        break;
                }
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_select_depot;
            }
        };

        adapter.setOnItemClickListener(new NormalAdapter.OnItemClickListener<Object>() {
            @Override
            public void onItemClick(ViewHolder viewHolder, Object data, int position) {

                switch (action) {
                    //公司的选择  单选
                    case AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT:

                        ArrayList<OperateCompanyInfo> companyInfos = datas;
                        OperateCompanyInfo onclickItem = (OperateCompanyInfo) data;

                        for (OperateCompanyInfo item : companyInfos) {
                            if (item.getId().equals(onclickItem.getId())) {
                                item.setSelected(!onclickItem.isSelected());
                            }
                            //
                            else {
                                item.setSelected(false);
                            }

                            if (item.isSelected()) {
                                selectBean = item;
                            }

                        }

                        break;

                    //作业人员选择  多选
                    case AppConfig.BaseDataAction.OPERATE_PERSON_SELECT:

                        OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean person =
                                (OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean) data;

                        person.setSelected(!person.isSelected());
                        break;

                    //作业模式选择 多选
                    case AppConfig.BaseDataAction.OPERATE_MODL_SELECT:

                        OperateModle mode = (OperateModle) data;
                        mode.setSelected(!mode.isSelected());

                        break;
                }


                adapter.notifyDataSetChanged();

            }
        });

        search_rv.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.VERTICAL));
        search_rv.setLayoutManager(new LinearLayoutManager(this));
        search_rv.setAdapter(adapter);

        if (AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT.equals(action)) {
            setTitleShow("作业公司");
            getOperateCompany();
        }
        //
        else if (AppConfig.BaseDataAction.OPERATE_PERSON_SELECT.equals(action)) {
            setTitleShow("作业人员");
            getOperateCompany();
        }
        else if (AppConfig.BaseDataAction.OPERATE_MODL_SELECT.equals(action)) {
            setTitleShow("作业模式");
            getOperateModes();
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            collectCheck();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 采集选择
     */
    private void collectCheck() {
        //选公司
        if (AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT.equals(action)) {
            if (selectBean == null) {
                finish();
                return;
            }
        }
        //选人
        else if (AppConfig.BaseDataAction.OPERATE_PERSON_SELECT.equals(action)) {

            ArrayList<OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean> temp = datas;

            selectBeans = new ArrayList();

            for (OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean item : temp) {
                if (item.isSelected())
                    selectBeans.add(item);
            }

            if (selectBeans.size() == 0) {
                finish();
                return;
            }
        }
        //选模式
        else if (AppConfig.BaseDataAction.OPERATE_MODL_SELECT.equals(action)) {
            ArrayList<OperateModle> temp = datas;
            selectBeans = new ArrayList();

            for (OperateModle item : temp) {
                if (item.isSelected())
                    selectBeans.add(item);
            }

            if (selectBeans.size() == 0) {
                finish();
                return;
            }
        }

        DialogUtils.showDialog(OperateSelectActivity.this, "提示", "确定选择吗?", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                onSureSelect();
            }
        }).show();
    }


    /**
     * 确定选择
     */
    private void onSureSelect() {
        Intent intent = new Intent();

        if (AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT.equals(action)) {
            intent.putExtra("selectBean", selectBean);
        }
        // 选人员或者选模式
        else {
            intent.putExtra("selectBeans", selectBeans);
        }

        this.setResult(RESULT_OK, intent);
        finish();
    }


    /**
     * 作业公司查询
     *
     */
    private void getOperateCompany() {

        if (!StringUtils.isCanUse(factoryId))
            factoryId = "5a8bf057-d7c8-4b99-a33a-db04654e09a5";

        //开始进行网络的访问
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        mApiService.getOperateList(factoryId)
                .compose(RxSchedulers.<BaseInfo<List<OperateCompanyInfo>>>compose(this))
                .subscribe(new BaseObserver<List<OperateCompanyInfo>>(this) {
                    @Override
                    public void onSuccess(BaseInfo<List<OperateCompanyInfo>> baseInfo) {
                        if (baseInfo != null) {

                            if (baseInfo.getData() != null) {
                                datas.clear();

                                //这里分选择公司或者选择人员
                                if (AppConfig.BaseDataAction.OPERATE_PERSON_SELECT.equals(action)) {
                                    for (OperateCompanyInfo oif : baseInfo.getData()) {
                                        if (companyId.equals(oif.getId())) {
                                            ArrayList<OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean> basOperatePersonListBeans = new ArrayList<>();
                                            for (OperateCompanyInfo.BasOperateTeamListBean btlb : oif.getBasOperateTeamList()) {
                                                if (btlb.getBasOperatePersonList() != null)
                                                    basOperatePersonListBeans.addAll(btlb.getBasOperatePersonList());
                                            }

                                            datas.addAll(basOperatePersonListBeans);
                                            break;
                                        }
                                    }
                                }
                                //
                                else {
                                    datas.addAll(baseInfo.getData());
                                }

                                //添加一份缓存
                                datas_cache.addAll(datas);

                                adapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        Toast.makeText(OperateSelectActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 作业模式查询
     */
    private void getOperateModes() {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        mApiService.getOperateModes()
                .compose(RxSchedulers.<BaseInfo<List<OperateModle>>>compose(this))
                .subscribe(new BaseObserver<List<OperateModle>>(this) {
                    @Override
                    public void onSuccess(BaseInfo<List<OperateModle>> baseInfo) {
                        if (baseInfo != null && baseInfo.getData() != null) {
                            datas.addAll(baseInfo.getData());
                            adapter.notifyDataSetChanged();

                            //添加一份缓存
                            datas_cache.addAll(datas);
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

}








